#include "Timer.h"

#include "SensirionSht11.h"

#include "printf.h"

#include "TestSensorMessage.h"

module  TestSensorC{

uses interface Boot;

uses interface Leds;

uses interface Read<uint16_t> as readTemp;

uses interface Read<uint16_t> as readHumidity;

uses interface Read<uint16_t> as readPhoto;

uses interface Timer<TMilli> as SampleTimer;

uses interface SplitControl as Control;

uses interface AMSend;

uses interface Packet;

}

implementation

{
	
	
	#define SAMPLING_FREQUENCY 100

	bool locked = FALSE;
	
	message_t packet;
	
	uint16_t TempData;

	uint16_t HumidityData;

	uint16_t PhotoData;

	//fa song han shu
	void Send(nx_uint8_t Type, nx_uint16_t Data)
	{
		if(locked){
			return;
		  }
		  else{
		  
			  sensor_msg_t* rcm = (sensor_msg_t *)call Packet.getPayload(&packet,sizeof(sensor_msg_t));
			  if(rcm == NULL) {return;}
			  if(call Packet.maxPayloadLength() < sizeof(sensor_msg_t)){
				return;
			  }
			  
			  rcm->Type = Type;
			  rcm->Data = Data;
			  
			  if(call AMSend.send(AM_BROADCAST_ADDR,&packet,sizeof(sensor_msg_t)) == SUCCESS){
				locked = TRUE;
			  }
		  }
	}

	event void Boot.booted() 
	{
		//call SampleTimer.startPeriodic(SAMPLING_FREQUENCY);
		call Control.start();	//启动通信模块
	}

	event void SampleTimer.fired()
	{
		call readTemp.read();//读取温度值

		call readHumidity.read();//读取湿度值

		call readPhoto.read();//读取光照值
	}

	event void readTemp.readDone(error_t result, uint16_t val) 
	{
		if (result == SUCCESS)
		{
			val = -40.1+ 0.01*val;//转换成摄氏度值，这个公式根据SHT11数据手册
			TempData = val;
		}

		else TempData = 0xffff;
		  //printf("TempData : %u\n", TempData);
		  
		Send(0,TempData);
		
		call Leds.led0Toggle();
	}

	event void readHumidity.readDone(error_t result, uint16_t val) 
	{
		if (result == SUCCESS)
		{
			HumidityData = -4 + 4*val/100 + (-28/1000/10000)*(val*val);//转换成带温度补偿的湿度值
			HumidityData = (TempData-25)*(1/100+8*val/100/1000)+HumidityData;//但结果不知道这个转换公式转换的结果对不对
		}
		else HumidityData = 0xffff;

		  //printf("HumidityData : %u\n", HumidityData );
			
		  Send(1,HumidityData);

		call Leds.led1Toggle();		
	}

	event void readPhoto.readDone(error_t result, uint16_t val) 
	{

		if (result == SUCCESS)
		{
			PhotoData = val;
		}
		else PhotoData = 0xffff;
		//printf("PhotoData : %u\n", PhotoData );
		  
		  Send(2,PhotoData);
		
		call Leds.led2Toggle();
	}
	
	event void AMSend.sendDone(message_t *bufPtr, error_t error){
		if(&packet == bufPtr){
			locked = FALSE;
		}
	}
	
	event void Control.startDone(error_t err){
		if(err == SUCCESS){
			call SampleTimer.startPeriodic(SAMPLING_FREQUENCY);
		}
	}
	
	event void Control.stopDone(error_t err){
	
	}
}